package com.vision.core.sv.util;

import java.util.Calendar;
import java.util.Date;

/**
 * Server-side utility class for date and time-related operations.
 * 
 * NOTE: Due to its dependence on {@link Calendar}, it cannot be used in the
 * client side since GWT does not emulate the {@link Calendar} class.
 * 
 * @author Mark
 *
 */
public class DateUtils {
	
	public static final int DAY_AS_MILLIS = (24 * 60 * 60 * 1000);
	
	public static Date startOfDay(Date date) {
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		
		cal.set(Calendar.HOUR_OF_DAY, 0);
		cal.set(Calendar.MINUTE, 0);
		cal.set(Calendar.SECOND, 0);
		cal.set(Calendar.MILLISECOND, 0);
		
		return cal.getTime();
	}
	
	public static Date endOfDay(Date date) {
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		
		cal.set(Calendar.HOUR_OF_DAY, 23);
		cal.set(Calendar.MINUTE, 59);
		cal.set(Calendar.SECOND, 59);
		cal.set(Calendar.MILLISECOND, 999999);
		
		return cal.getTime();
	}
	
	public static Calendar calFromDate(Date date) {
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		return cal;
	}
	
	public static long dayDifference(Date date1, Date date2) {
		Date d1 = startOfDay(date1);
		Date d2 = startOfDay(date2);
		
		return (long) (d2.getTime() - d1.getTime()) / DAY_AS_MILLIS;
	}

}
